import moment from "moment";
import React, { PureComponent } from "react";
import { FlatList } from "react-native";
import { ScrollView, View, StyleSheet, Text, DeviceEventEmitter } from "react-native";
import CodePush from "react-native-code-push";
import DeviceInfo from 'react-native-device-info';
import { Button, CheckBox, Icon } from "react-native-tengits-elements";
import { Colors, FontSize } from "../common/Theme/TTheme";
import { scaleSize } from "../common/Utils/ToolUtils";
import MQTTServer from "../libs/MQTTServer";
import Utils from "../libs/Utils";
import CommunicationManager from "../logic/CommunicationManager";
import DataCenter from "../logic/DataCenter";
import { MQTT_CONNECT_STATUS, RegisterType } from "../logic/LogicConstant";
import { closeTopicDebug, setTopicDebug, query_topic_records, isTopicDebug, getTopicFilterFlag, setTopicFilterFlag } from "../logic/TopicDebugUtils";
import { getMasterNodeLocalSubscriberTopics, getMasterRemoteSubscriberTopics, getNormalNodeLocalSubscriberTopics, getNormalRemoteSubscriberTopics, getRequestTopics, getResponseTopics, getTopicMapping } from "../logic/TopicUtil";

export default class TestPage extends React.PureComponent {
    constructor(props) {
        super(props);
        let flag = getTopicFilterFlag();
        this.state = {
            machineIp: "",
            brokerRunnig: false,
            topicList: query_topic_records(),
            topicDebugStatus: isTopicDebug(),
            apiLevel:0,
            filterRemote: flag&1,
            filterLocal: flag&2,
            filterSend: flag&4,
            filterReceive: flag&8,
        };
        this.topicListener = null;
    }

    async componentDidMount() {
        this.setState({
            machineIp: await Utils.getMachineIp(),
            brokerRunnig: await MQTTServer.isMQTTServiceRunning(),
            apiLevel : await DeviceInfo.getApiLevel(),
        });
    }

    componentWillUnmount() {
        if(this.topicListener) {
            this.topicListener.remove();
            this.topicListener = null;
        }
    }

    topicDebug() {
        this.setState({
            topicList:[...query_topic_records()]
        });
    }

    transConnetStatus(status) {
        if(status == MQTT_CONNECT_STATUS.CONNECT_NONE) {
            return "无连接";
        } else if(status == MQTT_CONNECT_STATUS.CONNECT_ERROR) {
            return "连接错误";
        } else if(status == MQTT_CONNECT_STATUS.CONNECT_CLOSE) {
            return "连接已关闭";
        } else if(status == MQTT_CONNECT_STATUS.CONNECT_SUCCESS) {
            return "成功连接";
        } else {
            return "状态未知：" + status;
        }
    }

    getTitle(item) {
        let title = "";
        if(item.isRemote) { 
            title = "远程";
        } else {
            title = "本地";
        }

        if(item.isSend) {
            title += "(发送的消息)";
        } else {
            title += "(接收的消息)";
        }
        return title;
    }

    renderListItem = ({item, index, separators}) => {
        return <View style={[{flexDirection:'column', marginBottom:scaleSize(10), backgroundColor:'#F8F2D7'}, item.isSend ? {backgroundColor:'#DCDDF8'} : {}]}>
                <Text style={item.isRemote ? {backgroundColor:'green'} : {backgroundColor:'red'}}>{`${this.getTitle(item)}  ${item.time}`}</Text>
                <Text style={{backgroundColor:Colors.button_color}}>{item.topic}</Text>
                <Text>{item.isSend ?  JSON.stringify(item.payload) : item.payload}</Text>
            </View>
    }

    render() {
        const{navigation} = this.props;
        const{machineIp, topicDebugStatus, brokerRunnig, topicList, filterLocal, filterRemote, filterSend, filterReceive, apiLevel} = this.state;
        return <View style={{flex:1, backgroundColor:'white', }}>
            <View style={styles.header}>
                <Text style={{fontSize: FontSize.h3_font, color: Colors.white}}>{"调试信息"}</Text>
                <Button 
                    containerStyle={{position:'absolute', top:0, left:0}}
                    buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='close' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        navigation.goBack();
                }}/>
            </View>
            <View style={{flex:1, flexDirection:'row',}}>
                <ScrollView style={{flex:1,}} showsVerticalScrollIndicator={false}>
                    <Text>{"Android系统版本：" + DeviceInfo.getSystemVersion()}</Text>
                    <Text>{"Android API Level：" + apiLevel}</Text>
                    <Text>{"serverIp：" + DataCenter.serverIp}</Text>
                    <Text>{"serverId：" + DataCenter.serverId}</Text>
                    <Text>{"是否master：" + (DataCenter.isMaster ? "是" : "否")}</Text>
                    <Text>{"masterIp：" + DataCenter.masterIp}</Text>
                    <Text>{"masterId：" + DataCenter.masterId}</Text>
                    <Text>{"DataCenter中本机ip：" + DataCenter.machineIp}</Text>
                    <Text>{"动态获取本机ip：" + machineIp}</Text>
                    <Text>{"本机gateId：" + DataCenter.gateId}</Text>
                    <Text>{"本机注册情况：" + (DataCenter.registerStatus == RegisterType.REGISTER_SUCCESS ? "已注册" : "未注册")}</Text>
                    <Text>{"broker是否运行：" + (brokerRunnig ? "已运行" : "未运行")}</Text>
                    <Text>{"本地 mqtt client 状态：" + this.transConnetStatus(CommunicationManager.localMqttConnectStatus)}</Text>
                    <Text>{"远程 mqtt client 状态：" + this.transConnetStatus(CommunicationManager.remoteMqttConnectStatus)}</Text>
                    <Text>{"本地订阅topic：\n" + (DataCenter.isMaster? getMasterNodeLocalSubscriberTopics().join("\n") : getNormalNodeLocalSubscriberTopics().join("\n"))}</Text>
                    <Text>{"远程订阅topic：\n" + (DataCenter.isMaster? getMasterRemoteSubscriberTopics().join("\n") : getNormalRemoteSubscriberTopics().join("\n"))}</Text>
                    <View style={{flexDirection:'row', justifyContent:'space-around', marginTop:scaleSize(30)}}>
                        <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                        titleStyle={{fontSize: FontSize.h4_font}}
                        title={"清空缓存"}
                        onPress={async()=>{
                            await DataCenter.doRegister("", "");
                            CodePush.restartApp();
                        }}/>
                        <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                            titleStyle={{fontSize: FontSize.h4_font}}
                            title={topicDebugStatus ? "关闭Topic日志记录" : "开启Topic日志记录"} onPress={()=>{
                                if(topicDebugStatus) {
                                    closeTopicDebug();
                                    if(this.topicListener) {
                                        this.topicListener.remove();
                                        this.topicListener = null;
                                    }
                                    this.setState({
                                        topicDebugStatus: isTopicDebug(),
                                    });
                                } else {
                                    setTopicDebug();
                                    if(!this.topicListener) {
                                        this.topicListener = DeviceEventEmitter.addListener("topic_debug", this.topicDebug.bind(this));
                                    }
                                    this.setState({
                                        topicDebugStatus: isTopicDebug(),
                                    });
                                }
                        }}/>
                    </View>
                    <View style={{flexDirection:'row', flexWrap:'wrap', marginTop:scaleSize(30), marginBottom: scaleSize(30)}}>
                    <CheckBox
                        title='过滤远程'
                        checked={this.state.filterRemote}
                        onPress={() => {
                            setTopicFilterFlag(1, !this.state.filterRemote);
                            this.setState({filterRemote: !this.state.filterRemote});
                        }}
                        />
                    <CheckBox
                        title='过滤本地'
                        checked={this.state.filterLocal}
                        onPress={() => {
                            setTopicFilterFlag(2, !this.state.filterLocal);
                            this.setState({filterLocal: !this.state.filterLocal});
                        }}
                        />
                    <CheckBox
                        title='过滤发送'
                        checked={this.state.filterSend}
                        onPress={() => {
                            setTopicFilterFlag(4, !this.state.filterSend);
                            this.setState({filterSend: !this.state.filterSend});
                        }}
                        />
                    <CheckBox
                        title='过滤接收'
                        checked={this.state.filterReceive}
                        onPress={() => {
                            setTopicFilterFlag(8, !this.state.filterReceive);
                            this.setState({filterReceive: !this.state.filterReceive})
                        }}
                        />
                    </View>
                </ScrollView>
                <View style={{flex:1,}}>
                    <FlatList
                        style={{flex:1}}
                        ref={(ref)=>{this.listRef = ref}}
                        data={(topicList||[]).filter(item=> {
                            if(filterLocal && !item.isRemote) {
                                return false;
                            }
                            if(filterReceive && !item.isSend) {
                                return false;
                            }
                            if(filterRemote && item.isRemote) {
                                return false;
                            }
                            if(filterSend && item.isSend) {
                                return false;
                            }
                            return true;
                        })}
                        showsVerticalScrollIndicator={false}
                        renderItem={this.renderListItem}
                        keyExtractor={(item, index) => `${index}`}
                    />
                </View>
            </View>
        </View>
    }
}

const styles = StyleSheet.create({
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
        justifyContent:'center',
        alignItems:'center',
    },
});